package com.java.userservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.common.model.Result;
import com.java.common.util.DateUtil;
import com.java.common.util.FileUtil;
import com.java.common.util.JwtUtil;
import com.java.common.util.RedisUtil;
import com.java.manage.model.Company;
import com.java.manage.service.api.CompanyApiService;
import com.java.userservice.dao.UserMapper;
import com.java.userservice.dao.UserRoleMapper;
import com.java.userservice.dao.PermissionMapper;
import com.java.userservice.model.User;
import com.java.userservice.model.UserRole;
import com.java.userservice.model.Permission;
import com.java.userservice.model.Role;
import com.java.userservice.model.dto.UserRoleDTO;
import com.java.userservice.model.vo.PermissionVo;
import com.java.userservice.model.vo.TreeVo;
import com.java.userservice.service.UserRoleService;
import com.java.userservice.service.UserService;
import com.java.userservice.service.PermissionService;
import com.java.userservice.service.RoleService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserRoleService adminRoleService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private CompanyApiService companyApiService;

    @Override
    public Result login(User user) {
        String email = user.getUsername();
        int emails = email.indexOf("@");
        String regex = "[1][34578][0-9]{9}"; //手机号码的格式：第一位只能为1，第二位可以是3，4，5，7，8，第三位到第十一位可以为0-9中任意一个数字
        Scanner s = new Scanner(email); // 获取
        String number = s.next();
        if(number.matches(regex)){ // 判断是否为手机号 是则为手机号 登录
            user.setPhone(user.getUsername());
        } else if (emails != -1) { // 判断是否包含@ 包含则为邮箱 登录
            user.setEmail(user.getUsername());
        } else { // 否则用户名 登录。。。
            user.setUsername(user.getUsername());
        }

        User adm = userMapper.login(user);
        if (adm == null) {
            return Result.error("501", "用户名或密码错误！");
        }

        /*// 生成Token
        String token = UUID.randomUUID().toString().replace("-", "") + adm.getId();
        // 将Token存入redis中
        RedisUtil.addString(redisTemplate, "admin_" + adm.getId(), token, 30L);*/

        // 生成JWT Token
        Map map = new HashMap<>();
        map.put("id", adm.getId());
        map.put("username", adm.getUsername());
        RedisUtil.addString(redisTemplate, "id", String.valueOf(adm.getId()), 30L);
        RedisUtil.addString(redisTemplate, "username", adm.getUsername(), 30L);
        String token = JwtUtil.getToken(map);

        // 获取用户权限并存入redis中
        List<PermissionVo> permissionVos = permissionService.listByLoginId(adm.getId());
        List<Integer> ids = new ArrayList<>();

        for (PermissionVo permissionVo : permissionVos) {
            List<Permission> children = permissionVo.getChildren();
            List<Permission> permissions = new ArrayList<>();
            if (!CollectionUtils.isEmpty(children)) {
                for (Permission permission : children) {
                    if (ids.contains(permission.getId())) {
                        continue;
                    }
                    ids.add(permission.getId());
                    permissions.add(permission);
                }
            }
            permissionVo.setChildren(permissions);
        }
        String jsonStr = JSONObject.toJSONString(permissionVos);
        RedisUtil.addString(redisTemplate, "permission_" + adm.getId(), jsonStr, 30L);

        return Result.success(token);
    }

    @Override
    public Result upload(MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            // 生成目录
            String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
            //获取文件后缀名
            String suffix = filename.substring(filename.indexOf("."));
            // 生成文件新名称
            String newName = dateStr + "/" + UUID.randomUUID().toString() + suffix;

            ResponseMessage responseMessage = FileUtil.upload(file.getInputStream(), newName);
            return Result.success(responseMessage.getUri());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Result listRole() {
        List<Role> roles = roleService.listAll();

        List<TreeVo> treeVos = new ArrayList<>();

        if (!CollectionUtils.isEmpty(roles)) {
            for (Role role :  roles) {
                TreeVo treeVo = new TreeVo();
                treeVo.setId(role.getId());
                treeVo.setLabel(role.getName());
                treeVos.add(treeVo);
            }
        }
        return Result.success(treeVos);
    }

    @Override
    public Result listRoleByAdminId(Integer id) {
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        List<UserRole> list = userRoleMapper.list(userRole);
        List<Integer> roleIds = list.stream().map(UserRole::getRoleId).collect(Collectors.toList());

        return Result.success(roleIds);
    }

    @Override
    public Result saveRole(UserRoleDTO userRoleDTO) {
        adminRoleService.save(userRoleDTO);
        return Result.success();
    }

    @Override
    public Result userRole(User user) {
        PageHelper.startPage(user.getPageNum(), user.getPageSize());

        List<User> users = userMapper.userRole(user);
        PageInfo<User> pageInfo = new PageInfo<>(users);

        Map<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("total", pageInfo.getTotal());

        return Result.success(map);
    }

    @Override
    public Result save(User user) {
//        user.setType("2");
        userMapper.save(user);
        return Result.success();
    }

    @Override
    public Result modify(User user) {
        userMapper.modify(user);
        return Result.success();
    }

    @Override
    public Result remove(int[] ids) {
        for (int id : ids) {
            userMapper.remove(id);
        }
        return Result.success();
    }

    @Override
    public Result list(User user) {
        PageHelper.startPage(user.getPageNum(), user.getPageSize());

        List<User> list = userMapper.list(user);

        // 门店表
        List<Integer> storeCollect = list.stream().map(User::getStoreId).collect(Collectors.toList());
        List<Company> companies = companyApiService.listByIds(storeCollect);
        Map<Integer, Company> companyMap = companies.stream().collect(Collectors.toMap(company -> company.getId(), company -> company));
        list.stream().forEach(app -> {
            app.setCompany(companyMap.get(app.getStoreId()));
        });

        PageInfo<User> pageInfo = new PageInfo<>(list);

        Map<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("total", pageInfo.getTotal());

        return Result.success(map);
    }

    @Override
    public Result get(int id) {
        User user = userMapper.get(id);
        return Result.success(user);
    }
}
